package io.geekidea.boot.util.Base;

import com.aliyun.dingtalkyida_1_0.models.GetOpenUrlResponse;
import com.aliyun.dingtalkyida_2_0.models.GetFormDataByIDResponse;
import com.baiwang.open.entity.request.node.ImageInvoicesRecogcollectFileBase64Info;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.geekidea.boot.util.dingtalk.AuthTokenUtil;
import io.geekidea.boot.util.dingtalk.GetFormData;
import io.geekidea.boot.util.dingtalk.GetAttachmentsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ObtainNameAndBase64 {

    @Value("${ding-talk.app-key}")
    private String appKey;

    @Value("${ding-talk.app-secret}")
    private String appsecret;

    @Value("${ding-talk.app-type}")
    private String appType;

    @Value("${ding-talk.system-token}")
    private String systemToken;

    @Value("${ding-talk.user-id}")
    private String userId;

    @Value("${ding-talk.form-uuid-verify}")
    private String formUuidVerify;

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String BASE_URL = "https://y3uyhm.aliwork.com";

    /**
     * 生成附件Base64编码文件和文件名称
     *
     * @throws Exception
     */
    public List<ImageInvoicesRecogcollectFileBase64Info> getFlieBaseAndName(String instanceId) throws Exception {
        String accessToken = AuthTokenUtil.getAccessToken(appKey, appsecret).getAccessToken();
        log.info("token: " + accessToken);
        //根据实例ID调用宜搭接口获取表单信息
        GetFormDataByIDResponse formDataResponse = GetFormData.getFormDataResponse(accessToken, appType, systemToken, userId, formUuidVerify, instanceId);
        Map<String, ?> formData = formDataResponse.getBody().getFormData();
        if (formData == null) {
            log.info("请输入正确的实例ID");
         }
        //获取附件地址和名称
        List<String> strings = extractAndProcessAttachment(formData);


        List<String> resultList = new ArrayList<>();
        for (int i = 0; i < strings.size(); i += 2) {
            //调用获取宜搭附件临时免登地址
            GetOpenUrlResponse attachments = GetAttachmentsUtil.getAttachments(accessToken, appType, systemToken, userId, strings.get(i));
            String resultUrl = attachments.getBody().getResult();
            //调用转换工具类下载文件并转为Base64编码
            String doenloadBase64 = UrlToBase64Converter.downloadAndConvertToBase64(resultUrl);
            resultList.add(strings.get(i + 1));
            resultList.add(doenloadBase64);

            log.info("文件名: " + strings.get(i + 1));
            log.info("免登录下载地址: " + resultUrl);

        }
        //将结果列表转换为FileInfo列表
        List<ImageInvoicesRecogcollectFileBase64Info>  filesMap = convertToFileInfoList(resultList);
        return filesMap;

    }

    /**
     * 将获取数据中的附件字段进行解析和输出
     *
     * @param formData
     */
    public static List<String> extractAndProcessAttachment(Map<String, ?> formData) {
        try {
            // 获取附件字段的值
            Object attachmentObj = formData.get("attachmentField_mf24jkvu");
            if (attachmentObj == null) {
                System.out.println("未找到附件字段");
                return null;
            }

            // 将附件字符串解析为List<Map>
            List<Map<String, Object>> attachments = objectMapper.readValue(
                    attachmentObj.toString(),
                    new TypeReference<List<Map<String, Object>>>() {
                    }
            );

            List<String> list = new ArrayList<>();
            // 处理每个附件
            for (Map<String, Object> attachment : attachments) {
                String name = (String) attachment.get("name");
                String downloadUrl = (String) attachment.get("downloadUrl");

                // 拼接完整URL
                String fullDownloadUrl = BASE_URL + downloadUrl;

                list.add(fullDownloadUrl);
                list.add(name);
                // 输出结果
                log.info("文件名: " + name);
                log.info("登录下载地址: " + fullDownloadUrl);
            }
            return list;
        } catch (Exception e) {
            System.err.println("处理附件时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将结果列表转换为FileInfo列表
     *
     * @param resultList
     * @return
     */
    public static List<ImageInvoicesRecogcollectFileBase64Info> convertToFileInfoList(List<String> resultList) {
        List<ImageInvoicesRecogcollectFileBase64Info>  filesMap= new ArrayList<>();

        for (int i = 0; i < resultList.size(); i += 2) {
            if (i + 1 < resultList.size()) {
                ImageInvoicesRecogcollectFileBase64Info fileInfo = new ImageInvoicesRecogcollectFileBase64Info();
                // 偶数位置为文件名
                fileInfo.setFileName(resultList.get(i));
                // 奇数位置为Base64编码
                fileInfo.setFileBase64(resultList.get(i + 1));
                filesMap.add(fileInfo);
            }
        }
        return filesMap;
    }
}
